package com.rain.exception;

import com.rain.enums.ResponseCodeEnum;

/**
 * 业务异常类，用于封装自定义业务错误信息
 *
 * @author Rain
 */
public class BusinessException extends Exception {

    private ResponseCodeEnum codeEnum;
    private Integer code;
    private String message;

    /**
     * 构造函数：使用枚举定义错误码和消息
     */
    public BusinessException(ResponseCodeEnum codeEnum) {
        super(codeEnum.getMsg());
        this.codeEnum = codeEnum;
        this.code = codeEnum.getCode();
        this.message = codeEnum.getMsg();
    }

    /**
     * 构造函数：指定错误码和消息
     */
    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    /**
     * 构造函数：只传消息（默认 code = 500）
     */
    public BusinessException(String message) {
        super(message);
        this.message = message;
        this.code = 500; // 默认系统错误码
    }

    /**
     * 构造函数：带原始异常（如数据库异常等）
     */
    public BusinessException(String message, Throwable e) {
        super(message, e);
        this.message = message;
        this.code = 500;
    }

    /**
     * 构造函数：带原始异常和错误码
     */
    public BusinessException(Integer code, String message, Throwable e) {
        super(message, e);
        this.code = code;
        this.message = message;
    }

    /**
     * 构造函数：带原始异常和枚举
     */
    public BusinessException(ResponseCodeEnum codeEnum, Throwable e) {
        super(codeEnum.getMsg(), e);
        this.codeEnum = codeEnum;
        this.code = codeEnum.getCode();
        this.message = codeEnum.getMsg();
    }

    // ================== Getter & Setter ==================

    public ResponseCodeEnum getCodeEnum() {
        return codeEnum;
    }

    public void setCodeEnum(ResponseCodeEnum codeEnum) {
        this.codeEnum = codeEnum;
        if (codeEnum != null) {
            this.code = codeEnum.getCode();
            this.message = codeEnum.getMsg();
        }
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    // ================== toString ==================

    @Override
    public String toString() {
        return "BusinessException{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", codeEnum=" + codeEnum +
                '}';
    }
}
